<?php

ini_set('memory_limit', '1024M');
ini_set('auto_detect_line_endings', true);
set_time_limit(0);

if (!isset($_FILES['product_csv']) or !is_uploaded_file($_FILES['product_csv']['tmp_name'])) {
	$smarty->display('shop/products/import.tpl.html');
	exit;
}


$fh = fopen($_FILES['product_csv']['tmp_name'], 'r');
$smarty->assign('filename', $_FILES['product_csv']['name']);

$headers = fgetcsv($fh);

$products = array();

$errors = array();
$product_codes_seen = array();

$row_number = 1;
while($row = fgetcsv($fh)) {
	$row_number++;
	if (!$row[0]) continue;
	
	// Convert the row from being indexed, to associative
	$row_parsed = array('row_number' => $row_number);
	foreach($row as $i => $cell) {
		$row_parsed[strtolower(trim($headers[$i]))] = $cell;
	}
	
	// strip off the # prefix added to prevent product codes being treated as number
	$row_parsed['product code'] = preg_replace('/^#/', '', $row_parsed['product code']);
	$row_parsed['parent code']  = preg_replace('/^#/', '', $row_parsed['parent code']);
	
	// parse the categories
	#if (isset($row_parsed['categories'])) {
		$row_parsed['categories flat'] = $row_parsed['categories'];
		$categories = preg_split('/[\n\r]+/', $row_parsed['categories']);
		$row_parsed['categories'] = array();
		foreach($categories as $category) {
			if ($category) $row_parsed['categories'][] = preg_split('/\s*\|\s*/', trim($category));
		}
	#}
	
	// parse the related products
	#if (isset($row_parsed['related products'])) {
		$row_parsed['related products'] = preg_split('/[\n\r]+/', $row_parsed['related products']);
		if ($row_parsed['related products'][0] == '') unset($row_parsed['related products'][0]);
	#}
	
	// parse the attributes into associative array
	#if (isset($row_parsed['attributes'])) {
		$attributes = preg_split('/[\n\r]+/', $row_parsed['attributes']);
		$row_parsed['attributes'] = array();
		foreach($attributes as $attribute) {
			$attribute = preg_split('/\s*:\s*/', $attribute, 2);
			if (trim($attribute[0]) and isset($attribute[1])) {
				$row_parsed['attributes'][trim($attribute[0])] = trim($attribute[1]);
			}
		}
	#}
	
	// do the same for meta
	#if (isset($row_parsed['meta'])) {
		$metas = preg_split('/[\n\r]+/', $row_parsed['meta']);
		$row_parsed['meta'] = array();
		foreach($metas as $meta) {
			$meta = preg_split('/\s*:\s*/', $meta, 2);
			if (trim($meta[0]) and isset($meta[1])) {
				$row_parsed['meta'][trim($meta[0])] = trim($meta[1]);
			}
		}
	#}
	
	// parse the simple attributes
	#if (isset($row_parsed['simple attributes'])) {
		$sattributes = preg_split('/[\n\r]+/', $row_parsed['simple attributes']);
		$row_parsed['simple attributes'] = array();
		foreach($sattributes as $sattribute) {
			preg_match('/^(.*?)\s*\|\s*(.*?)$/', $sattribute, $matches);
			if(isset($matches[0])) {
				$attribute = array();
				$attribute['label'] = $matches[1];
				preg_match_all('/(?:^|\s+)([a-zA-Z0-9]*?)=((“|”)|\'|")(.*?)(?(3)(?:“|”)|(\2))/', $matches[2], $matches);
				for($i=0;$i<count($matches[0]);$i++) {
					if ($matches[1][$i] == 'values') {
						$values = preg_split('/,\s*/', $matches[4][$i]);
						$attribute[$matches[1][$i]] = array();
						foreach($values as $value) {
							preg_match('/^(.*?)(?:\[(\d+(?:\.\d+)?)\])?$/', $value, $matches1);
							$attribute[$matches[1][$i]][] = array('value' => $matches1[1], 'price' => (isset($matches1[2]) ? $matches1[2] : 0.00));
						}
					} else {
						$attribute[$matches[1][$i]] = $matches[4][$i];
					}
				}
				$row_parsed['simple attributes'][$attribute['label']] = $attribute;
			}
		}
	#}
	
	// parse the price(s)
	#if (isset($row_parsed['price'])) {
		$prices = preg_split('/[\n\r]+/', $row_parsed['price']);
		$row_parsed['price'] = array();
		foreach($prices as $price) {
			if ($price) {
				preg_match('/^(?:\[(\d+)\])?\s*(\d+(?:\.\d+)?)$/', $price, $matches);
				if (isset($matches[1])) $row_parsed['price'][] = array('price' => $matches[2], 'minimum_quantity' => $matches[1]);
			}
		}
	#}
	
	if ($row_parsed['parent code']) {
		if (isset($products[$row_parsed['parent code']])) {
			if (!isset($products[$row_parsed['parent code']]['children'])) $products[$row_parsed['parent code']]['children'] = array();
			$products[$row_parsed['parent code']]['children'][$row_parsed['product code']] = $row_parsed;
			if (in_array($row_parsed['product code'], array_keys($product_codes_seen))) $errors[$row_parsed['row_number']][] = "<strong>Product code</strong> must be unique.  Previously used at row {$product_codes_seen[$row_parsed['product code']]}.";
			$product_codes_seen[$row_parsed['product code']] = $row_parsed['row_number'];
		} else {
			// error - no parent product exists
			$errors[$row_parsed['row_number']][] = '<strong>Parent code</strong> is defined, but product does not exist with this code (must be defined above this row).';
		}
	} else {
		$products[$row_parsed['product code']] = $row_parsed;
		if (isset($product_codes_seen[$row_parsed['product code']])) $errors[$row_parsed['row_number']][] = "<strong>Product code</strong> must be unique.  Previously used at row {$product_codes_seen[$row_parsed['product code']]}.";
		$product_codes_seen[$row_parsed['product code']] = $row_parsed['row_number'];
	}
	
}

/*
 * SANITY CHECK DATA
 *
 */
foreach($products as $product) {
	#$errors[$product['row_number']] = array();
	if (!$product['title']) $errors[$product['row_number']][] = '<strong>Title</strong> must be set.';
	if (!count($product['categories'])) $errors[$product['row_number']][] = '<strong>Categories</strong> should contain at least one category.';
	
	$price_min_quantity_seen = array();
	foreach($product['price'] as $price) {
		if (isset($price_min_quantity_seen[$price['minimum_quantity']])) $errors[$product['row_number']][] = "<strong>Price</strong> contains multiple definitions for minimum quantity {$price['minimum_quantity']}.";
		$price_min_quantity_seen[$price['minimum_quantity']] = true;
	}
	
	foreach($product['simple attributes'] as $attribute_name => $attribute) {
		$seen = array();
		foreach($attribute['values'] as $value) {
			if (in_array($value['value'], $seen)) {
				$errors[$product['row_number']][$attribute_name.$value['value']] = "Simple attribute <strong>{$attribute_name}</strong> contains value <strong>{$value['value']}</strong> multiple times.";
			}
			$seen[] = $value['value'];
		}
	} 
	
	if (!isset($product['children']) or count($product['children']) == 0) {
		
		if (count($product['price']) == 0) $errors[$product['row_number']][] = "<strong>Price</strong> must be set.";
		if (!$product['vat rate']) $errors[$product['row_number']][] = "<strong>VAT rate</strong> must be set.";
		if ($product['stock control?'] and $product['stock level'] == null) $errors[$product['row_number']][] = "<strong>Stock control</strong> is enabled, but no <strong>stock level</strong> is set.";
		
	} else {
		
		if ($product['stock level']) $errors[$product['row_number']][] = "<strong>Stock level</strong> should only be set on child products.";
		
		$attribute_keys = array();
		foreach($product['children'] as $child) {
			foreach($child['attributes'] as $key => $value) {
				$attribute_keys[] = $key;
			}
			break;
		}
		if (count($attribute_keys) == 0) {
			$errors[$child['row_number']][] = 'Products with a <strong>parent code</strong> should contain at least one <strong>attribute</strong>.';
		}
		
		foreach($product['children'] as $child) {
			if ($child['title'])                   $errors[$child['row_number']][] = "<strong>Title</strong> must not be set (it should only be set in the parent product at row {$product['row_number']}).";
			if (count($child['categories']))       $errors[$child['row_number']][] = "<strong>Categories</strong> must not be set (it should only be set in the parent product at row {$product['row_number']}).";
			if ($child['description'])             $errors[$child['row_number']][] = "<strong>Description</strong> must not be set (it should only be set in the parent product at row {$product['row_number']}).";
			if ($child['short description'])       $errors[$child['row_number']][] = "<strong>Short description</strong> must not be set (it should only be set in the parent product at row {$product['row_number']}).";
			if ($child['range'])                   $errors[$child['row_number']][] = "<strong>Range</strong> must not be set (it should only be set in the parent product at row {$product['row_number']}).";
			if (count($child['price']) == 0 and count($product['price']) == 0) $errors[$child['row_number']][] = "<strong>Price</strong> must be set here or in parent product at row {$product['row_number']}.";
			if (!$child['vat rate'] and !$product['vat rate']) $errors[$child['row_number']][] = "<strong>VAT rate</strong> must be set here or in parent product at row {$product['row_number']}.";
			if ((($product['stock control?'] and $child['stock control?'] == null) or $child['stock control?']) and $child['stock level'] == null) $errors[$child['row_number']][] = "<strong>Stock control</strong> is enabled, but no <strong>stock level</strong> is set.";	
			if (count($child['attributes']) != count($attribute_keys)) $errors[$child['row_number']][] = "All child products should contain the same number of <strong>attributes</strong>.";
			else {
				foreach($attribute_keys as $key) {
					if (!isset($child['attributes'][$key])) {
						$errors[$child['row_number']][] = "All child products should contain the same <strong>attributes</strong>.";
						break;
					}
				}
			}
			foreach($child['simple attributes'] as $attribute_name => $attribute) {
				$seen = array();
				foreach($attribute['values'] as $value) {
					if (in_array($value['value'], $seen)) {
						$errors[$child['row_number']][$attribute_name.$value['value']] = "Simple attribute <strong>{$attribute_name}</strong> contains value <strong>{$value['value']}</strong> multiple times.";
					}
					$seen[] = $value['value'];
				}
			}
			if (count($child['related products'])) $errors[$child['row_number']][] = "<strong>Related</strong> items must not be set (they should only be set in the parent product at row {$product['row_number']}).";
			$price_min_quantity_seen = array();
			foreach($child['price'] as $price) {
				if (isset($price_min_quantity_seen[$price['minimum_quantity']])) $errors[$child['row_number']][] = "<strong>Price</strong> contains multiple definitions for minimum quantity {$price['minimum_quantity']}.";
				$price_min_quantity_seen[$price['minimum_quantity']] = true;
			}
		}
		
	}
	
	
}


if (count($errors) or $_REQUEST['dryrun']) {
	ksort($errors);
	$smarty->assign('errors', $errors);
	$smarty->display('shop/products/import.tpl.html');
	exit;
}


/*
 * DATA HAS BEEN PARSED AND VERIFIED SO CONTINUE TO PROCESS INTO DB
 *
 */
$related_products = array();
$product_codes_seen = array();
$root_category_id = $db->fetchOne("SELECT id FROM shop_categories WHERE site_id=? AND parent_id=0", $site['id']);

foreach($products as $product) {
	// if the cells are empty, we want to treat that as a null value
	foreach($product as $k => $v) {
		if ($v == '') $product[$k] = null;
	}
	
	$product_codes_seen[] = $product['product code'];
	
	$product['range_id'] = null;
	if ($product['range'] and !$product['range_id'] = $db->fetchOne("SELECT id FROM shop_ranges WHERE site_id=? AND title=?", array($site['id'], $product['range']))) {
		$db->insert('shop_ranges', array('site_id' => $site['id'], 'title' => $product['range']));
		$product['range_id'] = $db->lastInsertId();
	}
	
	$product_row = array(
		'path'              => (isset($product['path']) ? make_path($product['path']) : make_path($product['product code'])),
		'title'             => $product['title'],
		'range_id'          => $product['range_id'],
		'description'       => $product['description'],
		'short_description' => $product['short description'],
		'categories'        => $product['categories flat'],
		'stock_control'     => $product['stock control?'],
		'stock_level'       => $product['stock level'],
		'setup_price'       => $product['setup price'],
		'minimum_quantity'  => $product['minimum quantity'] ? $product['minimum quantity'] : 1,
		'multiples_of'      => $product['multiples of'] ? $product['multiples of'] : 1,
		'rrp'               => $product['rrp'],
		'cost'              => $product['cost'],
		'vat_rate'          => $product['vat rate'],
		'width'             => $product['width'],
		'height'            => $product['height'],
		'depth'             => $product['depth'],
		'weight'            => $product['weight'],
		'free_shipping'     => $product['free shipping?'] ? 1 : 0,
		'ships_in_min'      => $product['ships in (min)'],
		'ships_in_max'      => $product['ships in (max)'],
		'active'            => $product['active?'] ? 1 : 0,
		'deleted'           => 0
	);
	if ($product_id = $db->fetchOne("SELECT id FROM shop_products WHERE site_id=? AND code=?", array($site['id'], $product['product code']))) {
		// product exists
		$db->update('shop_products', $product_row, $db->quoteInto('id=?', $product_id));
		$db->delete('shop_categories_products', $db->quoteInto('product_id=?', $product_id));
	} else {
		// new product
		$product_row = array_merge($product_row, array('site_id' => $site['id'], 'code' => $product['product code'], 'purchase_count' => 0));
		$db->insert('shop_products', $product_row);
		$product_id = $db->lastInsertId();
	}
	$db->insert('shop_categories_products', array(
		'category_id' => $root_category_id,
		'product_id'  => $product_id,
		'master'      => 0
	));
	
	// create all categories if not created, and link in products
	foreach($product['categories'] as $category) {
		$parent_id = $root_category_id;
		foreach($category as $i => $title) {
			if (!$category_id = $db->fetchOne("SELECT id FROM shop_categories WHERE site_id=? AND parent_id=? AND title=?", array($site['id'], $parent_id, $category[$i]))) {
				$db->insert('shop_categories', array(
					'site_id'   => $site['id'],
					'parent_id' => $parent_id,
					'title'     => $category[$i],
					'path'      => make_path($category[$i]),
					'image'     => make_path($category[$i])
				));
				$category_id = $db->lastInsertId();
			}
			if (($master = $db->fetchOne("SELECT master FROM shop_categories_products WHERE category_id=? AND product_id=?", array($category_id, $product_id))) != null) {
				if ($master == 0 and $i == count($category)-1) {
					$db->update('shop_categories_products', array(
						'master' => 1
					), array($db->quoteInto('category_id=?', $category_id), $db->quoteInto($product_id)));
				}
			} else {
				$db->insert('shop_categories_products', array(
					'category_id' => $category_id,
					'product_id'  => $product_id,
					'master'      => ($i == count($category)-1 ? 1 : 0)
				));
			}
			$parent_id = $category_id;
		}
	}
	
	// prices
	$db->delete('shop_products_prices', $db->quoteInto('product_id=?', $product_id));
	foreach($product['price'] as $price) {
		$db->insert('shop_products_prices', array(
			'product_id'       => $product_id,
			'minimum_quantity' => $price['minimum_quantity'] ? $price['minimum_quantity'] : 1,
			'price'            => $price['price']
		));
	}
	
	// meta data
	$meta_ids = $db->fetchPairs("SELECT title, id FROM shop_products_metas WHERE title IN(" . join(',', array_merge(array('""'), array_map(create_function('$input', 'global $db; return $db->quote($input);'), array_keys($product['meta'])))) . ")");
	$db->delete('shop_products_metas_values', $db->quoteInto('product_id=?', $product_id));
	$sort = 0;
	foreach($product['meta'] as $meta_key => $meta_val) {
		// if the meta key isn't in the database already, add it
		if (!isset($meta_ids[$meta_key])) {
			$db->insert('shop_products_metas', array('title' => $meta_key));
			$meta_ids[$meta_key] = $db->lastInsertId();
		}
		$sort += 10;
		$db->insert('shop_products_metas_values', array(
			'product_id' => $product_id,
			'meta_id'    => $meta_ids[$meta_key],
			'value'      => $meta_val,
			'sort'       => $sort
		));
	}
	
	// attributes
	$attribute_ids = array();
	$attribute_values_sort = array();
	if (isset($product['children']) and count($product['children'])) {
		foreach($product['children'] as $child) {
			$attribute_ids = $db->fetchPairs("SELECT title, id FROM shop_products_attributes WHERE title IN(" . join(',', array_merge(array('""'), array_map(create_function('$input', 'global $db; return $db->quote($input);'), array_keys($child['attributes'])))) . ")");
			$db->delete('shop_products_attributes_products', $db->quoteInto('product_id=? AND attribute_id NOT IN (' . join(',', array_merge(array(0), array_values($attribute_ids))) . ')', $product_id));
			$sort = 0;
			foreach($child['attributes'] as $attribute_key => $attribute_val) {
				if (!isset($attribute_ids[$attribute_key])) {
					$db->insert('shop_products_attributes', array(
						'title' => $attribute_key
					));
					$attribute_ids[$attribute_key] = $db->lastInsertId();
				}
				$attribute_values_sort[$attribute_ids[$attribute_key]] = 0;
				$sort += 10;
				$db->query("INSERT INTO shop_products_attributes_products (product_id, attribute_id, sort) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE sort=?", array($product_id, $attribute_ids[$attribute_key], $sort, $sort));
			}
			break;
		}
	}
	
	// simple attributes
	$simpleattribute_ids = $db->fetchPairs("SELECT title, id FROM shop_products_simpleattributes WHERE title IN(" . join(',', array_merge(array('""'), array_map(create_function('$input', 'global $db; return $db->quote($input);'), array_keys($product['simple attributes'])))) . ")");
	$db->delete('shop_products_simpleattributes_products', $db->quoteInto('product_id=? AND simpleattribute_id NOT IN (' . join(',', array_merge(array(0), array_values($simpleattribute_ids))) . ')', $product_id));
	$db->delete('shop_products_simpleattributes_values', $db->quoteInto('product_id=?', $product_id));
	$sort = 0;
	foreach($product['simple attributes'] as $simpleattribute) {
		if (!isset($simpleattribute_ids[$simpleattribute['label']])) {
			$db->insert('shop_products_simpleattributes', array(
				'title'   => $simpleattribute['label'],
				'type'    => $simpleattribute['type'] ? $simpleattribute['type'] : 'select'
			));
			$simpleattribute_ids[$simpleattribute['label']] = $db->lastInsertId();
		}
		
		$sort += 10;
		$db->query("INSERT INTO shop_products_simpleattributes_products (product_id, simpleattribute_id, sort, `default`) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE sort=?, `default`=?", array(
			$product_id, 
			$simpleattribute_ids[$simpleattribute['label']], 
			isset($simpleattribute['sort']) ? $simpleattribute['sort'] : $sort, 
			isset($simpleattribute['default']) ? $simpleattribute['default'] : null, 
			isset($simpleattribute['sort']) ? $simpleattribute['sort'] : $sort, 
			isset($simpleattribute['default']) ? $simpleattribute['default'] : null
		));
		
		$sort1 = 0;
		if (isset($simpleattribute['values'])) {
			foreach($simpleattribute['values'] as $value) {
				$sort1 += 10;
				$db->insert('shop_products_simpleattributes_values', array(
					'product_id'         => $product_id,
					'simpleattribute_id' => $simpleattribute_ids[$simpleattribute['label']],
					'value'              => $value['value'],
					'price'              => $value['price'],
					'sort'               => $sort1
				));
			}
		}
		
	}
	
	// related products
	#print_r($product['related products']);
	foreach($product['related products'] as $code) {
		if (!isset($related_products[$product_id])) $related_products[$product_id] = array();
		$related_products[$product_id][] = $code; 
	}
	
	if (isset($product['children']) and count($product['children'])) {
		foreach($product['children'] as $child) {
			// if the cells are empty, we want to treat that as a null value
			foreach($child as $k => $v) {
				if ($v == '') $child[$k] = null;
			}
			
			$product_codes_seen[] = $child['product code'];
			
			$child_row = array(
				'parent_id'         => $product_id,
				'path'              => null,
				'title'             => null,
				'range_id'          => null,
				'description'       => null,
				'short_description' => null,
				'stock_control'     => $child['stock control?'],
				'stock_level'       => $child['stock level'],
				'setup_price'       => $child['setup price'],
				'minimum_quantity'  => $child['minimum quantity'],
				'multiples_of'      => $child['multiples of'],
				'rrp'               => $child['rrp'],
				'cost'              => $child['cost'],
				'vat_rate'          => $child['vat rate'],
				'width'             => $child['width'],
				'height'            => $child['height'],
				'depth'             => $child['depth'],
				'weight'            => $child['weight'],
				'free_shipping'     => $child['free shipping?'],
				'ships_in_min'      => $child['ships in (min)'],
				'ships_in_max'      => $child['ships in (max)'],
				'purchase_count'    => null,
				'active'            => $child['active?'],
				'deleted'           => 0
			);
			if ($child_id = $db->fetchOne("SELECT id FROM shop_products WHERE site_id=? AND code=?", array($site['id'], $child['product code']))) {
				// product exists
				$db->update('shop_products', $child_row, $db->quoteInto('id=?', $child_id));
			} else {
				// new product
				$child_row = array_merge($child_row, array('site_id' => $site['id'], 'code' => $child['product code']));
				$db->insert('shop_products', $child_row);
				$child_id = $db->lastInsertId();
			}
			
			// prices
			$db->delete('shop_products_prices', $db->quoteInto('product_id=?', $child_id));
			foreach($child['price'] as $price) {
				$db->insert('shop_products_prices', array(
					'product_id'       => $child_id,
					'minimum_quantity' => $price['minimum_quantity'] ? $price['minimum_quantity'] : 1,
					'price'            => $price['price']
				));
			}
			
			// meta data
			$meta_ids = $db->fetchPairs("SELECT title, id FROM shop_products_metas WHERE title IN(" . join(',', array_merge(array('""'), array_map(create_function('$input', 'global $db; return $db->quote($input);'), array_keys($child['meta'])))) . ")");
			$db->delete('shop_products_metas_values', $db->quoteInto('product_id=?', $child_id));
			$sort = 0;
			foreach($child['meta'] as $meta_key => $meta_val) {
				// if the meta key isn't in the database already, add it
				if (!isset($meta_ids[$meta_key])) {
					$db->insert('shop_products_metas', array('title' => $meta_key));
					$meta_ids[$meta_key] = $db->lastInsertId();
				}
				$sort += 10;
				$db->insert('shop_products_metas_values', array(
					'product_id' => $child_id,
					'meta_id'    => $meta_ids[$meta_key],
					'value'      => $meta_val,
					'sort'       => $sort
				));
			}
			
			// attributes
			$db->delete('shop_products_attributes_values', $db->quoteInto('product_id=?', $child_id));
			foreach($child['attributes'] as $attribute_key => $attribute_val) {
				$attribute_values_sort[$attribute_ids[$attribute_key]] += 10;
				$db->insert('shop_products_attributes_values', array(
					'product_id'   => $child_id,
					'attribute_id' => $attribute_ids[$attribute_key],
					'value'        => $attribute_val,
					'sort'         => $attribute_values_sort[$attribute_ids[$attribute_key]]
				));
			}
			
			// simple attributes
			$simpleattribute_ids = $db->fetchPairs("SELECT title, id FROM shop_products_simpleattributes WHERE title IN(" . join(',', array_merge(array('""'), array_map(create_function('$input', 'global $db; return $db->quote($input);'), array_keys($child['simple attributes'])))) . ")");
			$db->delete('shop_products_simpleattributes_products', $db->quoteInto('product_id=? AND simpleattribute_id NOT IN (' . join(',', array_merge(array(0), array_values($simpleattribute_ids))) . ')', $child_id));
			$db->delete('shop_products_simpleattributes_values', $db->quoteInto('product_id=?', $child_id));
			$sort = 0;
			foreach($child['simple attributes'] as $simpleattribute) {
				if (!isset($simpleattribute_ids[$simpleattribute['label']])) {
					$db->insert('shop_products_simpleattributes', array(
						'title' => $simpleattribute['label'],
						'type'  => $simpleattribute['type']
					));
					$simpleattribute_ids[$simpleattribute['label']] = $db->lastInsertId();
				}
				
				$sort += 10;
				$db->query("INSERT INTO shop_products_simpleattributes_products (product_id, simpleattribute_id, sort, `default`) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE sort=?, `default`=?", array(
					$child_id, 
					$simpleattribute_ids[$simpleattribute['label']], 
					isset($simpleattribute['sort']) ? $simpleattribute['sort'] : $sort, 
					isset($simpleattribute['default']) ? $simpleattribute['default'] : null, 
					isset($simpleattribute['sort']) ? $simpleattribute['sort'] : $sort, 
					isset($simpleattribute['default']) ? $simpleattribute['default'] : null
				));
				$sort1 = 0;
				if (isset($simpleattribute['values'])) {
					foreach($simpleattribute['values'] as $value) {
						$sort1 += 10;
						$db->insert('shop_products_simpleattributes_values', array(
							'product_id'         => $child_id,
							'simpleattribute_id' => $simpleattribute_ids[$simpleattribute['label']],
							'value'              => $value['value'],
							'price'              => $value['price'],
							'sort'               => $sort1
						));
					}
				}
			}
			
			#print_r($child);
			
		}
	}
	
}

// mark as deleted, any product that haven't appeared in this upload
$db->query("UPDATE shop_products SET deleted=1 WHERE site_id=? AND code NOT IN (" . join(',', array_map(create_function('$input', 'global $db; return $db->quote($input);'), $product_codes_seen)) . ")", $site['id']);

// link up the related products
foreach($related_products as $id => $products) {
	$db->delete('shop_products_related', array($db->quoteInto('site_id=?', $site['id']), $db->quoteInto('product_id=?', $id)));
	foreach($products as $product) {
		if ($product_id = $db->fetchOne("SELECT id FROM shop_products WHERE site_id=? AND code=? AND parent_id IS NULL", array($site['id'], $product))) {
			$db->insert('shop_products_related', array(
				'site_id'    => $site['id'],
				'product_id' => $id,
				'related_id' => $product_id
			));
		}
	}
}

$logger->debug('complete');
$smarty->display('shop/products/import.tpl.html');
